package visiopuce.ui.view;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.part.ViewPart;

import visiopuce.ApplicationContexte;
import visiopuce.objets.Analyse;
import visiopuce.objets.Personne;
import visiopuce.objets.Prelevement;
import visiopuce.objets.Resultat;
import visiopuce.service.AnalyseServiceImpl;
import visiopuce.service.PersonneService;
import visiopuce.service.PersonneServiceImpl;
import visiopuce.service.PrelevementServiceImpl;
import visiopuce.service.ResultatServiceImpl;
import visiopuce.ui.listener.DoubleCliqueResultatRechercheListener;
import visiopuce.ui.providers.NavigationContentProvider;
import visiopuce.ui.tree.AlterationNode;
import visiopuce.ui.tree.AnalyseNode;
import visiopuce.ui.tree.DossierNode;
import visiopuce.ui.tree.PrelevementNode;
import visiopuce.ui.tree.PuceNode;
import visiopuce.ui.tree.ResultatNode;
import visiopuce.ui.tree.ResultatRechercheNode;

public class ResultatRechercheView extends ViewPart {

	public static final String ID = "visiopuce.resultatRechercheDossierView";
	private TreeViewer treeViewer;
	private Label nombreResultat;

	public ResultatRechercheView() {
	}

	@Override
	public void createPartControl(Composite parent) {
		Composite c = new Composite(parent, SWT.NONE);
		c.setLayout(new GridLayout(1, true));
		nombreResultat = new Label(c, SWT.BORDER);

		treeViewer = new TreeViewer(c, SWT.FULL_SELECTION);
		treeViewer.setContentProvider(new NavigationContentProvider(true));

		TreeViewerColumn columnNom = new TreeViewerColumn(treeViewer, SWT.CENTER);
		columnNom.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof DossierNode) {
					DossierNode current = (DossierNode) element;
					if (current.getPersonne().getNom() != null) {
						chaine = current.getPersonne().getNom();
					}
				} else if (element instanceof PrelevementNode) {
					PrelevementNode current = (PrelevementNode) element;
					if (current.getPrelevement().getNumeroPrelevement() != null) {
						chaine = current.getPrelevement().getNumeroPrelevement();
						if (current.getPrelevement().getTypePrelevement() != null) {
							chaine += " (" + current.getPrelevement().getTypePrelevement().getLibelle() + ")";
						}
					}
				} else if (element instanceof PuceNode) {
					PuceNode current = (PuceNode) element;
					if (current.getName() != null) {
						chaine = current.getName();
					}
				} else if (element instanceof AnalyseNode) {
					AnalyseNode current = (AnalyseNode) element;
					if (current.getName() != null) {
						chaine = current.getName();
					}
				} else if (element instanceof AlterationNode) {
					AlterationNode current = (AlterationNode) element;
					if (current.getName() != null) {
						chaine = current.getName();
					}
				} else if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						chaine = "Résultat :" + current.getResultat().getResultat();
						if (current.getResultat().getDateRendu() != null) {
							Locale locale = Locale.getDefault();
							DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DATE_FIELD, locale);
							chaine += " le " + dateFormat.format(current.getResultat().getDateRendu()).toString();
						}

					}

				} else {
					chaine = element.toString();
				}
				return chaine;
			}

			@Override
			public Color getBackground(Object element) {
				Color color = super.getBackground(element);
				boolean nonrendu = false;
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						if (current.getResultat().getResultat().equals("Non rendu")) {
							color = new Color(Display.getCurrent(), 255, 220, 0);
							nonrendu = true;
						}
					} else {
						color = new Color(Display.getCurrent(), 255, 220, 0);
						nonrendu = true;
					}
					if (current.getResultat().getDateRendu() == null) {
						color = new Color(Display.getCurrent(), 255, 220, 0);
						nonrendu = true;
					}
					if (nonrendu && AnalyseServiceImpl.getInstance().isUrgent(current.getResultat().getAnalyse().getIdAnalyse())) {
						color = new Color(Display.getCurrent(), 255, 0, 0);
					}
				} else {
					color = super.getBackground(element);
				}
				if (element instanceof AnalyseNode) {
					AnalyseNode current = (AnalyseNode) element;
					if (current.getAnalyse() != null) {
						if (current.getAnalyse().isUrgent()) {
							boolean nonrenduP = false;
							List<Resultat> resultats = ResultatServiceImpl.getInstance().findAllByidAnalyse(current.getAnalyse().getIdAnalyse());
							if (resultats.size() > 0) {
								for (Resultat resultat : resultats) {
									if (resultat.getResultat().equals("Non rendu")) {
										nonrenduP = true;
									} else if (resultat.getDateRendu() == null) {
										nonrenduP = true;
									}
								}
								if (nonrenduP) {
									color = new Color(Display.getCurrent(), 255, 0, 0);
								}
							} else {
								color = new Color(Display.getCurrent(), 255, 0, 0);
							}
						} else {
							color = super.getBackground(element);
						}

					} else {
						color = super.getBackground(element);
					}
				}
				if (element instanceof DossierNode) {
					color = new Color(Display.getCurrent(), 200, 200, 200);
				}
				
				return color;
			}
		});
		columnNom.getColumn().setText("Nom / numéro du prélèvement");
		columnNom.getColumn().setWidth(150);

		TreeViewerColumn columnPrenom = new TreeViewerColumn(treeViewer, SWT.CENTER);
		columnPrenom.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof DossierNode) {
					DossierNode current = (DossierNode) element;
					if (current.getPersonne().getPrenom() != null) {
						chaine = current.getPersonne().getPrenom();
					}
				}
				if (element instanceof PrelevementNode) {
					PrelevementNode current = (PrelevementNode) element;
					if (current.getPrelevement().getCotationEnvoye() == 0) {
						chaine = "Cotation non envoyée";
					}
					if (current.getPrelevement().getCotationEnvoye() == 1) {
						chaine = "Cotation à envoyer";
					}
					if (current.getPrelevement().getCotationEnvoye() == 2) {
						chaine = "Cotation envoyée";
					}
				}
				return chaine;
			}

			@Override
			public Color getBackground(Object element) {
				Color color = super.getBackground(element);
				boolean nonrendu = false;
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						if (current.getResultat().getResultat().equals("Non rendu")) {
							color = new Color(Display.getCurrent(), 0, 255, 0);
							nonrendu = true;
						}
					} else {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					if (current.getResultat().getDateRendu() == null) {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					Analyse ana = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
					if (nonrendu && ana.isUrgent()) {
						color = new Color(Display.getCurrent(), 255, 0, 0);
					}
				} else {
					color = super.getBackground(element);
				}
				if (element instanceof DossierNode) {
					color = new Color(Display.getCurrent(), 200, 200, 200);
				}
				if (element instanceof PrelevementNode) {
					if (element instanceof PrelevementNode) {
						PrelevementNode current = (PrelevementNode) element;
						if (current.getPrelevement().getCotationEnvoye() == 0) {
							color = new Color(Display.getCurrent(), 255, 0, 0);
						}
						if (current.getPrelevement().getCotationEnvoye() == 1) {
							color = new Color(Display.getCurrent(), 85, 103, 239);
						}
						if (current.getPrelevement().getCotationEnvoye() == 2) {
							color = new Color(Display.getCurrent(), 132, 255, 178);
						}
					}
				}
				return color;
			}
		});
		columnPrenom.getColumn().setText("Prénom");
		columnPrenom.getColumn().setWidth(150);

		TreeViewerColumn columnDateN = new TreeViewerColumn(treeViewer, SWT.CENTER);
		columnDateN.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof DossierNode) {
					DossierNode current = (DossierNode) element;
					Locale locale = Locale.getDefault();
					DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DATE_FIELD, locale);
					if (current.getPersonne().getDateNaissance() != null) {
						chaine = dateFormat.format(current.getPersonne().getDateNaissance()).toString();
					}
				}
				return chaine;
			}

			@Override
			public Color getBackground(Object element) {
				Color color = super.getBackground(element);
				boolean nonrendu = false;
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						if (current.getResultat().getResultat().equals("Non rendu")) {
							color = new Color(Display.getCurrent(), 0, 255, 0);
							nonrendu = true;
						}
					} else {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					if (current.getResultat().getDateRendu() == null) {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					Analyse ana = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
					if (nonrendu && ana.isUrgent()) {
						color = new Color(Display.getCurrent(), 255, 0, 0);
					}
				} else {
					color = super.getBackground(element);
				}
				if (element instanceof DossierNode) {
					color = new Color(Display.getCurrent(), 200, 200, 200);
				}

				return color;
			}
		});
		columnDateN.getColumn().setText("Date de naissance");
		columnDateN.getColumn().setWidth(150);

		// TreeViewerColumn columnSecteur = new TreeViewerColumn(viewer,
		// SWT.CENTER);
		// columnSecteur.setLabelProvider(new ColumnLabelProvider() {
		// public String getText(Object element) {
		// String chaine = "";
		// if (element instanceof AnalyseNode) {
		// AnalyseNode current = (AnalyseNode) element;
		// if (current.getAnalyse().getLaboratoire().getSecteur()
		// .getLibelle() != null) {
		// chaine = current.getAnalyse().getLaboratoire()
		// .getSecteur().getLibelle();
		// }
		// }
		// return chaine;
		// }
		// });
		// columnSecteur.getColumn().setText("Secteur");
		// columnSecteur.getColumn().setWidth(50);
		//
		// TreeViewerColumn columnLabo = new TreeViewerColumn(viewer,
		// SWT.CENTER);
		// columnLabo.setLabelProvider(new ColumnLabelProvider() {
		// public String getText(Object element) {
		// String chaine = "";
		// if (element instanceof AnalyseNode) {
		// AnalyseNode current = (AnalyseNode) element;
		// if (current.getAnalyse().getLaboratoire().getLibelle() != null) {
		// chaine = current.getAnalyse().getLaboratoire()
		// .getLibelle();
		// }
		// }
		// return chaine;
		// }
		// });
		// columnLabo.getColumn().setText("Laboratoire");
		// columnLabo.getColumn().setWidth(30);

		TreeViewerColumn columnTypeAna = new TreeViewerColumn(treeViewer, SWT.CENTER);
		columnTypeAna.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof PuceNode) {
					PuceNode current = (PuceNode) element;
					if (current.getPuce().getTypePuce() != null && current.getPuce().getTypePuce().getLibelle() != null) {
						chaine = current.getPuce().getTypePuce().getLibelle();
					}
				} else if (element instanceof AnalyseNode) {
					AnalyseNode current = (AnalyseNode) element;
					if (current.getAnalyse().getTypeAnalyse().getLibelle() != null) {
						chaine = current.getAnalyse().getTypeAnalyse().getLibelle();
					}
				}
				return chaine;
			}

			@Override
			public Color getBackground(Object element) {
				Color color = super.getBackground(element);
				boolean nonrendu = false;
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						if (current.getResultat().getResultat().equals("Non rendu")) {
							color = new Color(Display.getCurrent(), 0, 255, 0);
							nonrendu = true;
						}
					} else {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					if (current.getResultat().getDateRendu() == null) {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					Analyse ana = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
					if (nonrendu && ana.isUrgent()) {
						color = new Color(Display.getCurrent(), 255, 0, 0);
					}
				} else {
					color = super.getBackground(element);
				}
				if (element instanceof DossierNode) {
					color = new Color(Display.getCurrent(), 200, 200, 200);
				}

				return color;
			}
		});
		columnTypeAna.getColumn().setText("Type d'analyse");
		columnTypeAna.getColumn().setWidth(150);

		TreeViewerColumn columnResultat = new TreeViewerColumn(treeViewer, SWT.CENTER);
		columnResultat.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					chaine = "Formule:" + current.getResultat().getFormule();
				}
				return chaine;
			}

			@Override
			public Color getBackground(Object element) {
				Color color = super.getBackground(element);
				boolean nonrendu = false;
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						if (current.getResultat().getResultat().equals("Non rendu")) {
							color = new Color(Display.getCurrent(), 0, 255, 0);
							nonrendu = true;
						}
					} else {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					if (current.getResultat().getDateRendu() == null) {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					Analyse ana = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
					if (nonrendu && ana.isUrgent()) {
						color = new Color(Display.getCurrent(), 255, 0, 0);
					}
				} else {
					color = super.getBackground(element);
				}
				if (element instanceof DossierNode) {
					color = new Color(Display.getCurrent(), 200, 200, 200);
				}

				return color;
			}
		});
		columnResultat.getColumn().setText("Résultats");
		columnResultat.getColumn().setWidth(150);

		TreeViewerColumn columnDateResultat = new TreeViewerColumn(treeViewer, SWT.CENTER);
		columnDateResultat.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				String chaine = "";
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					Locale locale = Locale.getDefault();
					DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DATE_FIELD, locale);
					if (current.getResultat().getDateRendu() != null) {
						if (dateFormat.format(current.getResultat().getDateRendu()).toString() != null) {
							chaine = dateFormat.format(current.getResultat().getDateRendu()).toString();
						} else {
							chaine = "non rendu";
						}
					} else {
						chaine = "non rendu";
					}
				}
				return chaine;
			}

			@Override
			public Color getBackground(Object element) {
				Color color = super.getBackground(element);
				boolean nonrendu = false;
				if (element instanceof ResultatNode) {
					ResultatNode current = (ResultatNode) element;
					if (current.getResultat() != null) {
						if (current.getResultat().getResultat().equals("Non rendu")) {
							color = new Color(Display.getCurrent(), 0, 255, 0);
							nonrendu = true;
						}
					} else {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					if (current.getResultat().getDateRendu() == null) {
						color = new Color(Display.getCurrent(), 0, 255, 0);
						nonrendu = true;
					}
					Analyse ana = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
					if (nonrendu && ana.isUrgent()) {
						color = new Color(Display.getCurrent(), 255, 0, 0);
					}
				} else {
					color = super.getBackground(element);
				}
				if (element instanceof DossierNode) {
					color = new Color(Display.getCurrent(), 200, 200, 200);
				}

				return color;
			}
		});
		columnDateResultat.getColumn().setText("Date de rendu");
		columnDateResultat.getColumn().setWidth(150);

		Tree tree = treeViewer.getTree();
		tree.setLayoutData(new GridData(GridData.FILL_BOTH));

		tree.setHeaderVisible(true);
		tree.setLinesVisible(true);
		treeViewer.addDoubleClickListener(new DoubleCliqueResultatRechercheListener());
	//	treeViewer.getTree().addListener(SWT.MouseHover, new Listener() {

			// @Override
			// public void selectionChanged(SelectionChangedEvent event) {
			// IStructuredSelection selection = (IStructuredSelection)
			// event.getSelection();
			// Object element = selection.getFirstElement();
			//
			// if (element instanceof ResultatNode ) {
			// event.getSource()
			// columnDateResultat.getColumn().
			// ResultatNode current = (ResultatNode) element;
			// Analyse analyse =
			// AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
			// Prelevement prelevement =
			// PrelevementServiceImpl.getInstance().getPrelevementById(analyse.getPrelevement().getIdPrelevement());
			// Personne personne =
			// PersonneServiceImpl.getInstance().getPersonneById(prelevement.getPersonne().getIdPersonne());
			// SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
			// final String nomFichierResultat =
			// prelevement.getNumeroPrelevement() + "_" + personne.getNom() +
			// "_" + personne.getPrenom() + "_caryo_" +
			// formatter.format(current.getResultat().getDateRendu()) + ".docx";
			// File fichierResultat = new
			// File(ApplicationContexte.REPERTOIRE_RESULTAT +
			// nomFichierResultat);
			// if (fichierResultat.exists()) {
			// try {
			// Desktop desktop = Desktop.getDesktop();
			// desktop.open(fichierResultat);
			// } catch (IOException e1) {
			// // TODO Auto-generated catch block
			// e1.printStackTrace();
			// }
			// }
			// }
			// }

//			@Override
//			public void handleEvent(Event event) {
//				Rectangle r = event.getBounds();
//				ViewerCell vc = treeViewer.getCell(new Point(r.x, r.y));
//				if (vc != null && vc.getText() != null && vc.getText().contains("Fichier")) {
//					IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection();
//					Object element = selection.getFirstElement();
//					if (element instanceof ResultatNode) {
//						ResultatNode current = (ResultatNode) element;
//						Analyse analyse = AnalyseServiceImpl.getInstance().getAnalyseByIdAnalyse(current.getResultat().getAnalyse().getIdAnalyse());
//				
//					}
//				}
//			}
//		});

	}

	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}

	public void refresh() {
		PersonneService personneService = PersonneServiceImpl.getInstance();
		if (ApplicationContexte.getInstance().getRechercheEnCours() != null) {
			ResultatRechercheNode rrNode = new ResultatRechercheNode(personneService.findAllByRecherche(ApplicationContexte.getInstance().getRechercheEnCours()));
			treeViewer.setInput(rrNode);
			treeViewer.refresh();
			treeViewer.expandToLevel(4);
			nombreResultat.setText("Nombre de dossiers trouvés : " + rrNode.getNbPersonne());
			nombreResultat.pack();
		}
	}
}
